import { reqUserLogoutInfo, reqPhoneCodeInfo, reqRegisterOkInfo, reqUserLoginInfo, reqUserInfo } from "@/api";
import { setToken, getToken, removeToken } from '@/utils/token';
//用户

export default {
    state: {
        code: '',
        token: getToken(),
        userInfo: {}
    },
    actions: {
        //获取验证码
        async getPhoneCode({ commit }, phone) {
            let result = await reqPhoneCodeInfo(phone);
            if (result.code === 200) {
                commit('GEIPHONECODE', result.data);
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        },
        //完成注册
        async getRegisterOk({ commit }, data) {
            let result = await reqRegisterOkInfo(data);
            if (result.code === 200) {
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        },
        //用户登录
        async getUserLogin({ commit }, data) {
            let result = await reqUserLoginInfo(data);
            if (result.code === 200) {
                commit('GETUSERLOGIN', result.data.token);
                setToken(result.data.token);
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        },
        //获取用户信息
        async getUserInfo({ commit }) {
            let result = await reqUserInfo();
            if (result.code === 200) {
                commit('GETUSERINFO', result.data);
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        },
        //退出登录
        async getUserLogout({ commit }) {
            let result = await reqUserLogoutInfo();
            if (result.code === 200) {
                commit('CLEAR');
                return 'ok';
            } else {
                return Promise.reject(new Error('faile'));
            }
        }
    },
    mutations: {
        GEIPHONECODE(state, code) {
            state.code = code;
        },
        GETUSERLOGIN(state, token) {
            state.token = token;
        },
        GETUSERINFO(state, userInfo) {
            state.userInfo = userInfo;
        },
        //退出登录以后清除与相应用户信息
        CLEAR(state) {
            state.token = '';
            state.userInfo = '';
            removeToken();
        }
    },
    getters: {

    }
}